package com.linjacy.container.product.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.linjacy.container.product.dao.LogisticsDao;
import com.linjacy.container.product.dao.TransporterDao;
import com.linjacy.container.product.dao.UserDao;
import com.linjacy.container.product.entity.LogisticsEntity;
import com.linjacy.container.product.service.MerchandiseService;
import com.linjacy.container.product.service.StandardService;
import com.linjacy.container.product.service.UserService;
import com.linjacy.container.product.vo.OrderVo;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.linjacy.common.utils.PageUtils;
import com.linjacy.common.utils.Query;

import com.linjacy.container.product.dao.OrderDao;
import com.linjacy.container.product.entity.OrderEntity;
import com.linjacy.container.product.service.OrderService;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import javax.swing.filechooser.FileSystemView;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {
    @Autowired
    LogisticsDao logisticsDao;
    @Autowired
    MerchandiseService merchandiseService;
    @Autowired
    StandardService standardService;
    @Autowired
    UserService userService;
    @Autowired
    UserDao userDao;
    @Autowired
    OrderDao orderDao;
    @Autowired
    TransporterDao transporterDao;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils getOrderPage(Map<String, Object> params) {
        IPage<OrderVo> page=new Page<>();
        String past1 = (String) params.get("past");
        int past = Integer.parseInt(past1);
        QueryWrapper wrapper=new QueryWrapper();
        if(past==1){
            wrapper.eq("status",1);
        }else{
            wrapper.ne("status",1);
        }
        String query = (String) params.get("query");
        if(!StringUtils.isEmpty(query)){
            query="%"+query+"%";
            wrapper.like("cid",query);
        }
        Integer selectCount = baseMapper.selectCount(wrapper);
        long count = selectCount.longValue();
        Object current = params.get("page");
        Long current1 = Long.valueOf(String.valueOf(current));
        Object size = params.get("limit");
        Long pageSize = Long.valueOf(String.valueOf(size));
        List<OrderVo> orderVos=new ArrayList<>();
        Long currentPage=(current1-1)*pageSize;
        if(past==1){
            orderVos = baseMapper.selectOrderVo(1,1,currentPage, pageSize,query);
        }else{
            orderVos = baseMapper.selectOrderVo(0,2,currentPage, pageSize,query);
        }
        page.setSize(pageSize);
        page.setTotal(count);
        page.setRecords(orderVos);
        return new PageUtils(page);
    }

    @Override
    public void saveOrder(OrderEntity order) {
        order.setStartTime(new Date());
        baseMapper.insert(order);
        userDao.changeOrderStatus(order.getUid());
    }

    @Override
    public void updateByOrderVo(OrderVo orderVo) {
        OrderEntity orderEntity=new OrderEntity();
        BeanUtils.copyProperties(orderVo,orderEntity);
        Long cid = orderVo.getCid();
        OrderEntity orderEntity1 = baseMapper.selectById(cid);
        Long uid = orderEntity1.getUid();
        int i = baseMapper.updateById(orderEntity);
        if(orderVo.getUid()!=uid){
            QueryWrapper<OrderEntity> wrapper=new QueryWrapper<>();
            Integer selectCount = orderDao.selectCountByUid(uid);
            if (selectCount==0){
                userDao.updateOrderStatus(uid);
            }
            Integer count = orderDao.selectCountByUid(orderVo.getUid());
            if (count!=0){
                userDao.changeOrderStatus(orderVo.getUid());
            }
        }

    }

    @Override
    public void deleteById(Long cid) {
        baseMapper.deleteById(cid);
    }

    @Override
    public void changeOrderStatus(Long cid) {
        Date date = new Date();
        baseMapper.updateOrderStatus(cid,date);
    }

    @Override
    @Transactional
    public void changeTransporterAndOrder(Map<String, Object> params) {
        LogisticsEntity logisticsEntity=new LogisticsEntity();
        String tId = (String) params.get("transporterId");
        String oId = (String) params.get("orderId");
        Long transporterId=Long.parseLong(tId.trim());
        Long orderId=Long.parseLong(oId.trim());
        orderDao.changeOrderStatus(orderId);
        transporterDao.changeTransporterStatus(1,transporterId);
        logisticsEntity.setCid(orderId);
        logisticsEntity.setLogisticsId(getId(oId.trim()));
        logisticsEntity.setStartTime(new Date());
        logisticsEntity.setTransporterId(transporterId);
        logisticsDao.insert(logisticsEntity);
    }

    @Override
    public void export(Map<String, Object> params,String fileName,HttpServletResponse response) throws Exception{
        List<Map<String, Object>> listVo= (List) params.get("list");
        FileSystemView fsv = FileSystemView.getFileSystemView();
        File home = fsv.getHomeDirectory();
        String savePath = home.getPath();
//        File excelFile = new File(savePath+"/"+ fileName + ".xls");
        // 声明一个工作薄
        HSSFWorkbook workbook = new HSSFWorkbook();
        //合并单元格样式
        HSSFCellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setAlignment(HorizontalAlignment.CENTER);//水平居中
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中
        //字体加粗
        HSSFFont font = workbook.createFont();
        font.setColor(HSSFColor.WHITE.index);
        font.setBold(true);

        cellStyle.setFillForegroundColor(IndexedColors.ROYAL_BLUE.getIndex());
        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        cellStyle.setFont(font);
        //第一页,生成模型信息
        HSSFSheet sheet1 = workbook.createSheet("集装箱数据报表");
        HSSFRow row0 = sheet1.createRow(0);
        HSSFCell cell0 = row0.createCell(0);
        cell0.setCellValue("订单号");
        cell0.setCellStyle(cellStyle);
        HSSFCell cell1 = row0.createCell(1);
        cell1.setCellValue("用户名称");
        cell1.setCellStyle(cellStyle);
        HSSFCell cell2 = row0.createCell(2);
        cell2.setCellValue("货物编号");
        cell2.setCellStyle(cellStyle);
        HSSFCell cell3 = row0.createCell(3);
        cell3.setCellValue("货物名称");
        cell3.setCellStyle(cellStyle);
        HSSFCell cell4 = row0.createCell(4);
        cell4.setCellValue("集装箱体积");
        cell4.setCellStyle(cellStyle);
        HSSFCell cell5 = row0.createCell(5);
        cell5.setCellValue("泡/重货");
        cell5.setCellStyle(cellStyle);
        HSSFCell cell6 = row0.createCell(6);
        cell6.setCellValue("集装箱类型");
        cell6.setCellStyle(cellStyle);
        HSSFCell cell7 = row0.createCell(7);
        cell7.setCellValue("集装箱承重");
        cell7.setCellStyle(cellStyle);
        HSSFCell cell8 = row0.createCell(8);
        cell8.setCellValue("发货地");
        cell8.setCellStyle(cellStyle);
        HSSFCell cell9 = row0.createCell(9);
        cell9.setCellValue("收货地");
        cell9.setCellStyle(cellStyle);
        HSSFCell cell10 = row0.createCell(10);
        cell10.setCellValue("发货时间");
        cell10.setCellStyle(cellStyle);
        HSSFCell cell11 = row0.createCell(11);
        cell11.setCellValue("收货时间");
        cell11.setCellStyle(cellStyle);
        sheet1.setColumnWidth(0, 14 * 256);
        sheet1.setColumnWidth(1, 14* 256);
        sheet1.setColumnWidth(2, 14 * 256);
        sheet1.setColumnWidth(3, 14 * 256);
        sheet1.setColumnWidth(4, 14 * 256);
        sheet1.setColumnWidth(5, 14 * 256);
        sheet1.setColumnWidth(6, 14 * 256);
        sheet1.setColumnWidth(7, 14 * 256);
        sheet1.setColumnWidth(8, 25 * 256);
        sheet1.setColumnWidth(9, 25 * 256);
        sheet1.setColumnWidth(10, 25 * 256);
        sheet1.setColumnWidth(11, 25 * 256);
        for (int i = 1; i <=listVo.size(); i++) {
            HSSFRow row = sheet1.createRow(i);
            HSSFCell cell110 = row.createCell(0);
            HSSFCell cell12 = row.createCell(1);
            HSSFCell cell13 = row.createCell(2);
            HSSFCell cell14 = row.createCell(3);
            HSSFCell cell15 = row.createCell(4);
            HSSFCell cell16 = row.createCell(5);
            HSSFCell cell17 = row.createCell(6);
            HSSFCell cell18 = row.createCell(7);
            HSSFCell cell19 = row.createCell(8);
            HSSFCell cell20 = row.createCell(9);
            HSSFCell cell21 = row.createCell(10);
            HSSFCell cell22 = row.createCell(11);
            cell110.setCellValue(listVo.get(i-1).get("cid").toString());
            cell12.setCellValue(listVo.get(i-1).get("uname").toString());
            cell13.setCellValue(listVo.get(i-1).get("mid").toString());
            cell14.setCellValue(listVo.get(i-1).get("mname").toString());
            cell15.setCellValue(listVo.get(i-1).get("volume").toString());
            String isHeavy=listVo.get(i-1).get("isHeavy").toString();
            if(isHeavy.equals("0")){
                cell16.setCellValue("重货");
            }else{
                cell16.setCellValue("泡货");
            }
            cell17.setCellValue(listVo.get(i-1).get("containerTypeName").toString());
            cell18.setCellValue(listVo.get(i-1).get("cload").toString());
            cell19.setCellValue(listVo.get(i-1).get("startPlace").toString());
            cell20.setCellValue(listVo.get(i-1).get("endPlace").toString());
            cell21.setCellValue(listVo.get(i-1).get("startTime").toString());
            cell22.setCellValue(listVo.get(i-1).get("endTime").toString());
        }
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");
        response.setContentType("application/octet-stream;charset=UTF-8");
        OutputStream osOut = response.getOutputStream();
        workbook.write(osOut);
        osOut.flush();
        osOut.close();
        workbook.close();
    }

    @Override
    public Map<String, Object> createAnalysis(Map<String, Object> params) {
        String start = (String) params.get("start");
        String end = (String) params.get("end");
        List<String> dateTime = orderDao.getDateTime(start, end);
        List<Integer> count=new ArrayList<>();
        for (int i = 0; i <dateTime.size() ; i++) {
            String time = dateTime.get(i)+"%";
            int orderCount = orderDao.getOrderCount(time);
            count.add(orderCount);
        }
        Map<String, Object> map=new HashMap<>();
        map.put("count",count);
        map.put("date",dateTime);
        return map;
    }

    @Override
    public List<Map<String, Integer>> getMapList() {
        List<Map<String, Integer>> city = orderDao.getCity();

        return city;
    }

    @Override
    public List<Map<String, String>> getNowOrder() {
        List<Map<String, String>> nowOrder = orderDao.getNowOrder();
        return nowOrder;
    }

    @Override
    public List<Map<String, Integer>> getBiscuit() {
        List<Map<String, Integer>> biscuit = orderDao.getBiscuit();
        return biscuit;
    }


    public  String getId(String order) {
        String logisticId =
                order +
                        (System.currentTimeMillis() + "").substring(1) +
                        (System.nanoTime() + "").substring(7, 10);
        System.out.println(logisticId);
        return logisticId;
    }

}